package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 密码形式认证服务
 */
@Service("password_auth_service")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CheckCodeClient checkCodeClient;


    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        // 校验验证码
        String key = authParamsDto.getCheckcodekey();
        String code = authParamsDto.getCheckcode();
        if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) throw new RuntimeException("验证码为空");
        Boolean verify = checkCodeClient.verify(key, code);
        if (!verify) throw new RuntimeException("验证码错误");

        // 根据账号查询用户信息
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getUsername, authParamsDto.getUsername());
        XcUser user = xcUserMapper.selectOne(queryWrapper);

        // 账号不存在
        if (user == null) throw new RuntimeException("账号不存在");

        // 创建拓展信息对象
        XcUserExt xcUserExt = new XcUserExt();
        // 对象拷贝
        BeanUtils.copyProperties(user, xcUserExt);

        // 获取用户提交的密码
        String passwordForm = authParamsDto.getPassword();
        // 获取数据库存储的正确密码
        String passwordDb = user.getPassword();
        // 密码匹配
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        // 匹配失败
        if (!matches) {
            throw new RuntimeException("账号或密码错误");
        }
        // 返回用户信息（带拓展的）
        return xcUserExt;
    }

}
